package com.np.ffmpeg4;

import static android.content.ContentValues.TAG;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.arthenica.ffmpegkit.FFmpegKit;
import com.arthenica.ffmpegkit.FFmpegSession;
import com.arthenica.ffmpegkit.FFmpegSessionCompleteCallback;
import com.arthenica.ffmpegkit.LogCallback;
import com.arthenica.ffmpegkit.MediaInformation;
import com.arthenica.ffmpegkit.MediaInformationJsonParser;
import com.arthenica.ffmpegkit.Statistics;
import com.arthenica.ffmpegkit.StatisticsCallback;
import com.np.ffmpeg4.utils.PathUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String[] PERMISSIONS_STORAGE = {android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final int REQUEST_EXTERNAL_STORAGE = 1;

    private static boolean havePermission = false;
    private TextView tvFile;
    private String mfile;

    private AlertDialog dialog;

    private void checkPermission() {
        //检查权限（NEED_PERMISSION）是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        //这里是android11以上的读写权限申请
        //需要通过Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION跳转到权限设置打开权限
        if (Build.VERSION.SDK_INT >= 30) {
            if (!Environment.isExternalStorageManager()) {
                if (dialog != null) {
                    dialog.dismiss();
                    dialog = null;
                }
                dialog = new AlertDialog.Builder(this)
                        .setTitle("提示")//设置标题
                        .setMessage("请开启文件访问权限，否则无法正常使用本应用！")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int i) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                                startActivity(intent);
                            }
                        }).create();
                dialog.show();
            } else {
                havePermission = true;
            }
        } else {
            //这里就是android7到android11的权限申请
            //直接通过ActivityCompat.requestPermissions就可以
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    if (dialog != null) {
                        dialog.dismiss();
                        dialog = null;
                    }
                    dialog = new AlertDialog.Builder(this)
                            .setTitle("提示")//设置标题
                            .setMessage("请开启文件访问权限，否则无法正常使用应用！")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                                }
                            }).create();
                    dialog.show();
                } else {
                    havePermission = true;

                }
            } else {
                //android7以下的不需要动态申请权限
                havePermission = true;

            }
        }
    }

    private void testReadFile() {
        File externalStorage = Environment.getExternalStorageDirectory();
        String path = externalStorage.getAbsolutePath();

        // 步骤1：创建一个File对象
        File file = new File(path + "/Android/ultrasound.mp4");

        try {
            // 步骤2：创建一个FileReader对象
            FileReader reader = new FileReader(file);

            // 步骤3：创建一个BufferedReader对象
            BufferedReader bufferedReader = new BufferedReader(reader);

            // 步骤4：逐行读取文件内容
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                // 在这里处理每一行的内容
                System.out.println(line);
            }

            // 步骤5：关闭BufferedReader和FileReader对象
            bufferedReader.close();
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkPermission();

        tvFile = findViewById(R.id.tvFile);

        findViewById(R.id.bFile).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                startActivityForResult(intent, 5);
            }
        });

        findViewById(R.id.bTest).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File externalStorage = Environment.getExternalStorageDirectory();
                String path = externalStorage.getAbsolutePath();

                // 步骤1：创建一个File对象
                //File file = new File(path + "/Android/ultrasound.mp4");
                File file = new File(mfile);

                try {
                    // 步骤2：创建一个FileReader对象
                    FileReader reader = new FileReader(file);

                    // 步骤3：创建一个BufferedReader对象
                    BufferedReader bufferedReader = new BufferedReader(reader);

                    // 步骤4：逐行读取文件内容
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        // 在这里处理每一行的内容
                        System.out.println(line);
                    }

                    // 步骤5：关闭BufferedReader和FileReader对象
                    bufferedReader.close();
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        findViewById(R.id.bPush).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 初始值
                String rtmp_url = "rtmp://live-push.bilivideo.com/live-bvc/?streamname=live_3546379957831915_58459438&key=56cc8bc5a338f4c3d9c5da8a46fe501a&schedule=rtmp&pflag=1";
                String image_path = mfile;
                String video_path = mfile;
                String push_video_command = "";
                String push_image_command = "";

                // 修改值
                //rtmp_url = "rtmp://100643.livepush.myqcloud.com/live/test?txSecret=c52887de1155d5166dca539e7f0634ac&txTime=656853B1";
                rtmp_url = "rtmp://192.168.2.156:10035/live/i6YJfdHSg?sign=ieL1BOHIgz";
                image_path = "/storage/emulated/0/DCIM/Camera/IMG_20231109_134441.jpg";
                video_path = "/storage/emulated/0/storage/emulated/0/Android/ultrasound.mp4";
                push_video_command = String.format("-re -i %s -c copy -f flv \"%s\"", video_path, rtmp_url);
                push_video_command = String.format("ffmpeg -i %s -c:v libx264 -c:a aac -f flv \"%s\"", video_path, rtmp_url);
                push_image_command = String.format("-loop 1 -i %s -vf \"scale=1280:720\" -r 30 -vcodec h264 -f flv \"%s\"", image_path, rtmp_url);

                // 同步
                // 解析推流域名时报错
                //FFmpegKit.execute(push_image_command);

                // 异步
                // 需要设置 android:hardwareAccelerated=“false“，否则会提示 The application may be doing too much work on its main thread
                FFmpegKit.executeAsync(push_video_command, new FFmpegSessionCompleteCallback() {
                    @Override
                    public void apply(FFmpegSession session) {
                        // 处理完成时的逻辑
                    }
                }, new LogCallback() {
                    @Override
                    public void apply(com.arthenica.ffmpegkit.Log log) {
                        // 日志处理
                    }
                }, new StatisticsCallback() {
                    @Override
                    public void apply(Statistics statistics) {
                        // 实时统计
                    }
                });

                //MediaInformation mediaInformation = MediaInformationJsonParser.from("MEDIA_INFORMATION_JPG");
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //申请文件读写权限
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_EXTERNAL_STORAGE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    havePermission = true;
                    Toast.makeText(this, "授权成功！", Toast.LENGTH_SHORT).show();
                } else {
                    havePermission = false;
                    Toast.makeText(this, "授权被拒绝！", Toast.LENGTH_SHORT).show();
                }
                break;
//            case REQUEST_PERMISSION_CODE_33:
//                Toast.makeText(this, "授权成功！", Toast.LENGTH_SHORT).show();
//                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 5 && data != null) {
            // /storage/emulated/0/storage/emulated/0/Android/ultrasound.mp4
            mfile = PathUtils.getPath(this, data.getData());
            tvFile.setText(mfile);
        }
    }
}